<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(text, index) in suggestions"
      :key="index"
      icon="search"
      @click="$emit('search',text)"
    >
    <div slot="title" v-html="highligh(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from "@/api/search";
import { debounce } from "lodash";
export default {
  name: "SearchSuggestion",
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestions: [] //联想建议数据列表
    };
  },
  computed: {},
  watch: {
    searchText: {
      // 防抖
      handler: debounce(function(value) {
        this.loadSearchSuggestions(value);
      },500),
      // handler(value) {
      //   this.loadSearchSuggestions(value);
      // },
      immediate: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearchSuggestions(q) {
      try {
        const { data } = await getSearchSuggestions(q);
        // console.log(data);
        this.suggestions = data.data.options;
      } catch (err) {
        this.$toast("数据获取失败，请稍后重试");
      }
    },
    highligh(text){
      const highlighStr=`<span style="color:red;">${this.searchText}</span>`
      const reg = new RegExp(this.searchText,'gi')
      return text.replace(reg,highlighStr)
    }
  }
};
</script>

<style scoped lang="less"></style>
